package com.ruoyi.hxf.controller;


import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;

import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;

import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;

import com.ruoyi.hxf.domain.Message;
import com.ruoyi.hxf.domain.Pay;
import com.ruoyi.hxf.domain.Pd;
import com.ruoyi.hxf.domain.bo.AdviceBo;
import com.ruoyi.hxf.domain.vo.AdviceVo;
import com.ruoyi.hxf.mapper.TypeMapper;
import com.ruoyi.hxf.service.IMessageService;

import com.ruoyi.hxf.service.IPayService;
import com.ruoyi.hxf.service.IPdService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import java.util.ArrayList;
import java.util.List;

/**
 * 消息 信息操作处理
 *
 * @author hxf
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/message")
public class MessageController extends BaseController {

    private final ISysUserService userService;
    private final IMessageService messageService;
    private final TypeMapper typeMapper;
    private final IPdService iPdService;
    private final IPayService iPayService;
    /**
     * 新增消息信息(电脑端)
     *
     * @param message 消息
     * @return 结果
     */
    @Log(title = "教育摘要", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/{msgIds}")
    public R<Void> add(@Validated @RequestBody Message message, @PathVariable Long[] msgIds) {
        Long userId = LoginHelper.getUserId();
        SysUser sysUser = userService.selectUserById(userId);
        String classId = typeMapper.selectFromClass(userId);
        message.setRemark(LoginHelper.getUsername());
        message.setMsgAvatar(sysUser.getAvatar());
        message.setCreateBy(classId);
        message.setCreateTime(DateUtils.getNowDate());
        message.setIsDelete("0");
        for (Long msgId : msgIds) {
            message.setReceiverId(String.valueOf(msgId));
            messageService.insertMessage(message);
        }
        message.setReceiverId(classId);
        message.setMsgId(null);
        messageService.insertMessage(message);
        return toAjax(true);
    }


    /**
     * 查询班级发送的信息列表
     *
     * @param message
     * @param pageQuery
     * @return
     */
//    @SaCheckPermission("advice:info:list")
    @GetMapping("/sendMessageList")
    public TableDataInfo<Message> sendMessageList(Message message, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        String deptId = typeMapper.selectFromClass(userId);
        message.setCreateBy(deptId);
        message.setReceiverId(deptId);
        message.setIsDelete(String.valueOf(1));
        TableDataInfo<Message> messageTableDataInfo = messageService.queryPageList(message, pageQuery);
        for (Message row : messageTableDataInfo.getRows()) {
            Long msgId = row.getMsgId();
            Message SimilarMessage = row;
            SimilarMessage.setMsgId(null);
            SimilarMessage.setReadStatus(1);
            row.setReadNumber(Math.toIntExact(messageService.selectSimilarMessageList(SimilarMessage)));
            SimilarMessage.setReadStatus(null);
            row.setReceiverId(String.valueOf(Math.toIntExact(messageService.selectSimilarMessageList(SimilarMessage) - 1)));
            if (row.getIsDelete().equals("0")) {
                row.setTopping(Long.valueOf(0));
            } else {
                row.setTopping(Long.valueOf(1));
            }
            row.setMsgId(msgId);
        }
        return messageTableDataInfo;
    }

    /**
     * 查询班级作业
     *
     * @return
     */
    @GetMapping("/homeWork/{classId}")
    public List<Message> getClassHomeWork(@PathVariable("classId") Long classId) {
        Long userId = LoginHelper.getUserId();
        Message message = new Message();
        message.setCreateBy(String.valueOf(classId));
        message.setReceiverId(String.valueOf(userId));
        message.setMsgStatus(1);
        List<Message> list = messageService.selectHomeWorkMessageList(message);
        return list;
    }

    /**
     * 分页查询班级作业
     *
     * @return
     */
    @GetMapping("/pageHomeWork/{classId}")
    public TableDataInfo<Message> getPageClassHomeWork(PageQuery pageQuery, @PathVariable("classId") Long classId) {
        Long userId = LoginHelper.getUserId();
        Message message = new Message();
        message.setCreateBy(String.valueOf(classId));
        message.setReceiverId(String.valueOf(userId));
        message.setMsgStatus(1);
        return messageService.selectPageHomeWorkMessageList(message, pageQuery);
    }

    /**
     * 查询自己的消息
     *
     * @return
     */
    @GetMapping("/myMessage")
    public List<Message> getMyMessage() {
        Long userId = LoginHelper.getUserId();
        Message message = new Message();
        message.setReceiverId(String.valueOf(userId));
        List<Message> list = messageService.selectMessageList(message);
        return list;
    }

    /**
     * 删除收到的消息信息（逻辑删除）
     *
     * @param msgIds 删除接受到的消息或者是发送的消息不会删除发送给别人的消息
     * @return
     */
    @Log(title = "删除收到的消息信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{msgIds}")
    public R<Void> remove(@PathVariable Long[] msgIds) {
        return toAjax(messageService.deleteMessageByIds(msgIds, 1));
    }

    /**
     * 撤回消息信息
     *
     * @param msgIds 撤回发送的消息
     * @return
     */
    @Log(title = "撤回消息信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updateStatus/{msgIds}")
    public R<Void> updateStatus(@PathVariable Long[] msgIds) {
        return toAjax(messageService.updateMessageByIds(msgIds));
    }

    /**
     * 置顶和是否读
     *
     * @param msgId
     * @return
     */
    @Log(title = "置顶和是否读", businessType = BusinessType.UPDATE)
    @PutMapping("/{msgId}/{value}")
    public R<Void> updateTopping(@PathVariable("msgId") Long msgId, @PathVariable("value") String value) {
        if (value.equals("1")) {
            Integer quantity = messageService.selectToppingQuantity();
            if (quantity == 0) {
                messageService.updateToppingQuantity(msgId, 1);
            } else {
                messageService.updateToppingQuantity(msgId, quantity + 1);
            }
        } else if (value.equals("2")) {
            messageService.updateToppingQuantity(msgId, 0);
        } else if (value.equals("3")) {
            messageService.updateReadStatus(msgId, 1);
        } else if (value.equals("4")) {
            messageService.updateReadStatus(msgId, 0);
        }

        return R.ok();
    }

    /**
     * 推送缴费提醒
     *
     * @param payId
     * @return
     */
    @Log(title = "推送缴费提醒", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/addPdMessage/{payId}")
    public R<Void> addPdMessage(@PathVariable Long payId) {
        List<Pd> pds = iPdService.selectPdByPayId(payId);
        Pay pay=iPayService.selectPayByPayId(payId);
        SysUser sysUser = userService.selectUserById(LoginHelper.getUserId());
        Message message = new Message();
        message.setCreateBy(String.valueOf(LoginHelper.getUserId()));
        message.setCreateTime(DateUtils.getNowDate());
        message.setRemark(LoginHelper.getUsername());
        message.setMsgAvatar(sysUser.getAvatar());
        message.setMsgTitle("请及时缴费！！！");
        message.setMsgStatus(0);
        message.setMsgContent(pay.getPayName()+",剩余缴费的时间不多了,请及时缴费！！！");
        for (Pd pd : pds) {
            message.setReceiverId(pd.getCreateBy());
            messageService.insertMessage(message);
        }
        return toAjax(true);
    }
}
